#!/usr/bin/env python
# -*- coding: utf8 -*-

import urllib
import simplejson

print "import mygoogle"

def html2txt(answer):
 replist = (
  ('<b>',       ''),
  ('</b>',      ''),
  ('&quot;',    '\"'),
  ('&#39;',     '\''),
  ('&amp;',     '&'),
  ('&middot;', u'·'),
  ('&gt;',      '>'),
  ('&lt;',      '<'),
 )
 return reduce(lambda a,x: a.replace(x[0],x[1]),replist,answer)


def google_handler(t, s, p, counter=1, site=('',)):
 if not p:
  s.msg(t,'?')
  return 

 answer=''

 import locale
 locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

 if type(p) == type(u""):
  p=p.encode('utf-8')

 for j in site:
  if j != '':
   pq = p + ' site:' + j
  else:
   pq = p
  query = urllib.urlencode({'q' : pq})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % (query)
  search_results = urllib.urlopen(url)
  json = simplejson.loads(search_results.read())
  c = counter
  for i in json['responseData']['results']:
   answer += u"%s\n%s\n%s\n\n" % (i['title'],i['content'], i['unescapedUrl'])
   c -= 1
   if c == 0:
    break

 if answer!='':
  s.msg(t,html2txt(answer))
 else:
  s.msg(t,'no results')

bot.register_cmd_handler(lambda t,s,p:google_handler(t, s, p, 1), '.g',5)
bot.register_cmd_handler(lambda t,s,p:google_handler(t, s, p, 2), '.g2',5)
bot.register_cmd_handler(lambda t,s,p:google_handler(t, s, p, 3), '.g3',5)
bot.register_cmd_handler(lambda t,s,p:google_handler(t, s, p, 4), '.g4',5)  

bot.register_cmd_handler(lambda t,s,p:google_handler(t, s, p, site=('ru.wikipedia.org',)), '.w',5)
bot.register_cmd_handler(lambda t,s,p:google_handler(t, s, p, site=('absurdopedia.wikia.com',)), '.a',5)
bot.register_cmd_handler(lambda t,s,p:google_handler(t, s, p, site=('wikipedia.org','absurdopedia.wikia.com','lurkmore.ru')), '.wiki',5)

def my_google_translate_handler(t, s, p, tolang='en'):
 from xgoogle.translate import Translator, TranslationError
 if type(p) == type(u""):
  p=p.encode('utf-8')
 er2 = False
 try:
  answer = Translator().translate(p, lang_to=tolang)
 except TranslationError:
  er2 = True
  if tolang == 'ru':
   fromlang = 'en'
  if tolang == 'en':
   fromlang = 'ru'
 if er2:
  try:
   answer = Translator().translate(p, lang_from=fromlang, lang_to=tolang)
  except TranslationError,e:
   return s.msg(t,e.message)
 if answer!='':
  s.msg(t,html2txt(answer))
 else:
  s.msg(t,'no results')

bot.register_cmd_handler(lambda t,s,p:my_google_translate_handler(t, s, p, 'en'), '.toen', 5)
bot.register_cmd_handler(lambda t,s,p:my_google_translate_handler(t, s, p, 'ru'), '.toru', 5)
bot.register_cmd_handler(lambda t,s,p:my_google_translate_handler(t, s, p, 'iw'), '.toiw', 5)

def my_google_langdetect_handler(t, s, p):
 from xgoogle.translate import Translator,LanguageDetector,DetectError
 if type(p) == type(u""):
  p=p.encode('utf-8')
 try:
  a = LanguageDetector().detect(p).lang
 except DetectError,e:
  return s.msg(t,e.message)
 if a!='':
  s.msg(t,"%s (%s)" % (Translator().translate(a, lang_to='ru'),a))
 else:
  s.msg(t,'no results')

bot.register_cmd_handler(my_google_langdetect_handler, '?lang', 5)

